package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import net.sf.json.JSONArray;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("commentsService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class CommentsService extends BaseServiceImpl<Comments> {

	@Resource
	private CommentsDao commentsDao;
	@Resource
	private UserDao userDao;
	@Resource
	private GoodsOrderDao goodsOrderDao;
	@Resource
	private Memcached memcached;
	@Resource
	private DdmGoodsDao ddmGoodsDao;
	@Resource
	private GoodSpecificationDao goodSpecificationDao;
	@Resource
	private ShopOrderDao shopOrderDao;

	@Override
	protected BaseDao <Comments> getDao() {
		return commentsDao;
	}

	/*
    *zlq
    *首页用户评价列表
    * @param  page:页码
    * @param  commentsPropertyValue : 评论类型值(必填) 1：最新（默认），2：晒图3：好评4：差评5：中评
    * @param  goodsId:商品ID
    *
     */
	public String getCommentsList(ModelMap model,String page,String commentsPropertyValue,String goodsId){
		PageView pageview =new  PageView();
		int pageNo = 1;
		int pageSize=20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if(!NumberUtils.isDigits(goodsId)){
			return CodeContent.getModelByCode(0, "商品ID不能为空", model);
		}
		DdmGoods ddmGoods=ddmGoodsDao.getById(Integer.parseInt(goodsId));
		if(ddmGoods==null){
			return CodeContent.getModelByCode(0, "商品不存在", model);
		}
		if(!NumberUtils.isDigits(commentsPropertyValue)){
			commentsPropertyValue="1";
		}
		if(CommentsProperty.getByIntValue(Integer.parseInt(commentsPropertyValue))==null){
			commentsPropertyValue="1";
		}
		Comments comments=new Comments();
		comments.setCommentsPropertyValue(Integer.parseInt(commentsPropertyValue));
		comments.setIsValid(true);
		comments.setGoodsId(ddmGoods.getId());
		pageview=commentsDao.queryPageView(pageNo,pageSize,comments);
		if (pageview != null){
			model.put("datas",convert_v1(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
			model.put("code",1);
			model.put("msg","success");
		}
		return  new JSONObject(model).toString();
	}

	public List<ModelMap> convert_v1(List<Comments> commentsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (commentsList != null && commentsList.size() > 0) {
			for (Comments comments : commentsList) {
				ModelMap map = buildModelList(comments);
				list.add(map);
			}
		}
		return list;
	}

	public ModelMap buildModelList(Comments comments ) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		ModelMap model = new ModelMap();
		User user=userDao.getById(comments.getUserId());
		String userName=user.getRealName();
		if(NumberUtils.isDigits(userName)){
			userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
		}
		model.put("id",comments.getId());
		model.put("userName",userName);
		model.put("avotorr",user.getAvotorr()!=null?user.getAvotorr():"");
		model.put("gradedValue",comments.getGradedValue());
		model.put("content",comments.getContent()!=null? comments.getContent():"" );
		model.put("imgUrl",comments.getImgUrl()!=null? comments.getImgUrl():"");
		model.put("replyMessage",comments.getReplyMessage()!=null? comments.getReplyMessage():"");
		model.put("createTime",formatter.format(comments.getCreateTime()));
		GoodsOrder goodsOrder=goodsOrderDao.getById(comments.getOrderId());
		if(goodsOrder.getGoodsSpecificationId()!=null){
			GoodSpecification goodSpecification =goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
			model.put("propertiesName",goodSpecification.getPropertiesName());
		}else {
			model.put("propertiesName","");
		}
		return  model;
	}

	/*
*获取评论统计数据
* zlq
* @param goodsId：商品id
*
 */
	public  String  commentsSumdatas(ModelMap modelMap,String goodsId){
		if(!NumberUtils.isDigits(goodsId)){
			return CodeContent.getModelByCode(0, "商品ID不能为空", modelMap);
		}
		DdmGoods ddmGoods=ddmGoodsDao.getById(Integer.parseInt(goodsId));
		List <CommentsProperty> commentsPropertyList =new ArrayList<CommentsProperty>();
		//展示评价统计信息
		commentsPropertyList.add(CommentsProperty.newComments);
		commentsPropertyList.add(CommentsProperty.Blueprinting);
		commentsPropertyList.add(CommentsProperty.GoodComments);
		commentsPropertyList.add(CommentsProperty.ZhongCustomers);
		commentsPropertyList.add(CommentsProperty.NegativeComments);
		List<Map> modelMapList=new ArrayList<Map>();
			for(CommentsProperty commentsProperty :commentsPropertyList){
				Map<String,Object> map = new HashMap<String, Object>();
				Integer count=0;
				if(ddmGoods!=null){
					Comments comments=new Comments();
					comments.setIsValid(true);
					comments.setGoodsId(ddmGoods.getId());
					comments.setCommentsProperty(commentsProperty);
					count=commentsDao.getCount(comments);
				}
				map.put("commentsPropertyValue",commentsProperty.getIntValue());
				map.put("commentsProperty",commentsProperty.toString());
				map.put("count",count);
				modelMapList.add(map);
			}
		return CodeContent.getModelByCode(1, "", modelMapList);
	}

/*
*zlq
* 添加评论
* token：
* datas：评论内容 json格式
* shopOrderId：二级订单ID
 */
	public String addComments(ModelMap model, String token, String datas ,String shopOrderId){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (StringUtils.isEmpty(datas)) {
			return CodeContent.getModelByCode(0, "数据不能为空", model);
		}
		if (!NumberUtils.isDigits(shopOrderId)) {
			return CodeContent.getModelByCode(0, "shopOrderId不能为空", model);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"addComments");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在5秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"addComments",5,"1");
		}
		ShopOrder shopOrder=shopOrderDao.getById(Integer.parseInt(shopOrderId));
		if(shopOrder==null){
			return CodeContent.getModelByCode(0, "二级订单ID不存在", model);
		}
		if(!shopOrder.getHasComment()){
			return CodeContent.getModelByCode(0, "该订单已经提交过评论了", model);
		}

		JSONArray jsonArray=null;
		try {
			jsonArray = JSONArray.fromObject(datas);//并将DS内容取出转为json数组
		}
		catch (Exception e){
			return CodeContent.getModelByCode(0, "解析出错，请确认您的格式正确", model);
		}
		List <Comments> commentsList =new ArrayList<Comments>();
		List <GoodsOrder> goodsOrderList =new ArrayList<GoodsOrder>();
		for (int i = 0; i < jsonArray.size(); i++) {     //遍历json数组内容
			net.sf.json.JSONObject object = jsonArray.getJSONObject(i);
			int goodId;
			try {
				goodId = object.getInt("goodId");
			}catch (Exception e){
				return CodeContent.getModelByCode(0, "获取商品id异常", model);
			}
			int orderId;
			try {
				orderId = object.getInt("orderId");
			}catch (Exception e){
				return CodeContent.getModelByCode(0, "获取三级订单id异常", model);
			}
			GoodsOrder goodsOrder=goodsOrderDao.getById(orderId);
			if(goodsOrder==null){
				return CodeContent.getModelByCode(0, "订单ID不存在", model);
			}
			if(goodsOrder.getUserId()-loginUser.getId()!=0){
				return CodeContent.getModelByCode(0, "该订单不是您的订单", model);
			}
			DdmGoods ddmGoods=ddmGoodsDao.getById(goodId);
			if(ddmGoods==null){
				return CodeContent.getModelByCode(0, "商品id不存在", model);
			}
			String content=object.getString("content");
			if(StringUtils.isEmpty(content)){
				content="好评！";
			}
			int gradedValue;
			try {
				gradedValue = object.getInt("gradedValue");
			}catch (Exception e){
				return CodeContent.getModelByCode(0, "model", model);
			}
			if(Graded.getByIntValue(gradedValue)==null){
				return CodeContent.getModelByCode(0, "分数值不正确", model);
			}
			String imgUrl=object.getString("imgUrl");
			Comments comments=new Comments();
		    comments.setUserId(loginUser.getId());
		    comments.setContent(content);
		    comments.setImgUrl(imgUrl);
		    comments.setOrderId(goodsOrder.getId());
		    comments.setCreateTime(new Date());
		    comments.setIsValid(true);
		    comments.setGoodsId(ddmGoods.getId());
		    comments.setGradedValue(gradedValue);
			commentsList.add(comments);
			goodsOrderList.add(goodsOrder);
		}
		for(GoodsOrder goodsOrder :goodsOrderList){
			goodsOrder.setHasComment(false);
			goodsOrderDao.modify(goodsOrder);
		}
		for(Comments comments:commentsList){
			commentsDao.add(comments);
		}
		shopOrder.setHasComment(false);
		shopOrderDao.modify(shopOrder);
		return CodeContent.getModelByCode(1, "", model);
	}

}